#!/usr/bin/env bash
# nginx

if [[ -z "${c_nginx}" ]]; then
    f_info 'nginx: not install';
    echo > /dev/null;  return;
fi;

f_wait 'nginx: install & config';

# install
f_inst 'nginx' 'nginx';  own='www:www';  dir='/home/www';
mkdir -p "${dir}/sock" || f_fail 'nginx: mkdir sock';
f_mode "${dir}/sock" '-' '700' "${own}";

# host
if [[ ! -d "${dir}/host/aac-default" ]]; then
    mkdir -p "${dir}/host" || f_fail 'nginx: mkdir host';
    f_copy "${RUN}/file/host" "${dir}/host/aac-default";
    f_mode "${dir}/host" '-' '700' "${own}";
fi;

# logs
mkdir -p "${dir}/logs" || f_fail 'nginx: mkdir logs';
mkdir -p '/var/log/nginx' || f_fail 'nginx: mkdir var/log';
f_link "${dir}/logs/ngx.err.log" '/var/log/nginx/error.log';
f_mode "${dir}/logs" '700' '-' "${own}";

# conf
cfg="${dir}/conf";  ngx="${cfg}/@ngx";
if [[ ! -d "${ngx}"  ]]; then
    not="${ngx}";  [[ ! -d "${cfg}" ]] && not="${cfg}";
    mkdir -p "${ngx}" || f_fail 'nginx: mkdir conf';
    f_mode "${not}" '755' '-' "${own}";
fi;
src="${RUN}/conf/nginx";  f_link '/etc/nginx' "${ngx}/.raw";
if [[ ! -f "${cfg}/ngx.conf" ]]; then
    f_copy "${src}/aac.conf" "${cfg}/ngx.conf" '755' '-' "${own}";
fi;
if [[ ! -f "${ngx}/aac.default.conf" ]]; then
    f_copy "${src}/default.conf" "${ngx}/aac.default.conf" '755' '-' "${own}";
fi;
f_bkup '/etc/nginx/nginx.conf';
f_link "${cfg}/ngx.conf" '/etc/nginx/nginx.conf';

# auto & start
f_auto 'nginx' 'nginx' 1;
systemctl restart nginx || f_fail 'nginx: restart srv';

echo > /dev/null;
